{"componentChunkName":"component---src-templates-post-jsx","path":"/[CS]이진탐색트리/","result":{"data":{"site":{"siteMetadata":{"title":"SUbbb"}},"markdownRemark":{"id":"2efb6036-05bf-594e-b9b5-03e399be6f78","excerpt":"🧷 이진 탐색 트리 이진 탐색 + 연결 리스트 이진 탐색 : 탐색에 소요되는 시간복잡도는 , 하지만 삽입, 삭제가 불가능 연결 리스트 : 삽입, 삭제의 시간복잡도는, 탐색하는 시간복잡도가  이 두 가지를 합하여 장점을 모두 얻어 효율적인 탐색 능력과 자료의 삽입, 삭제도 가능하게 하는 이진 탐색 트리 🪚 특징 노드에 저장된 키는 유일 (중복이 없어야 함)…","html":"<h2>🧷 이진 탐색 트리</h2>\n<blockquote>\n<p>이진 탐색 + 연결 리스트</p>\n</blockquote>\n<ul>\n<li><strong>이진 탐색</strong> : 탐색에 소요되는 시간복잡도는 <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>l</mi><mi>o</mi><mi>g</mi><mi>N</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(logN)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\" style=\"margin-right:0.01968em;\">l</span><span class=\"mord mathnormal\">o</span><span class=\"mord mathnormal\" style=\"margin-right:0.03588em;\">g</span><span class=\"mord mathnormal\" style=\"margin-right:0.10903em;\">N</span><span class=\"mclose\">)</span></span></span></span>, 하지만 삽입, 삭제가 불가능</li>\n<li><strong>연결 리스트</strong> : 삽입, 삭제의 시간복잡도는<span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mn>1</mn><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(1)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord\">1</span><span class=\"mclose\">)</span></span></span></span>, 탐색하는 시간복잡도가 <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>N</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(N)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\" style=\"margin-right:0.10903em;\">N</span><span class=\"mclose\">)</span></span></span></span></li>\n</ul>\n<p>이 두 가지를 합하여 장점을 모두 얻어 효율적인 탐색 능력과 자료의 삽입, 삭제도 가능하게 하는 <strong>이진 탐색 트리</strong></p>\n<h3>🪚 특징</h3>\n<ul>\n<li>노드에 저장된 키는 유일 (중복이 없어야 함)</li>\n<li>각 노드의 자식이 2개 이하</li>\n<li>각 노드의 왼쪽 자식은 부모보다 작고, 오른쪽 자식은 부모보다 큼</li>\n<li>왼쪽과 오른쪽 서브 트리도 이진 탐색 트리</li>\n</ul>\n<blockquote>\n<p><strong>중복이 없어야 하는 이유</strong></p>\n<p>: 검색 목적 자료구조인데, 굳이 중복이 많은 경우에 트리를 사용하여 검색 속도를 느리게 할 필요가 없다.</p>\n</blockquote>\n<p>이진 탐색 트리의 순회는 <strong>\"중위 순회(inorder)\"</strong> 방식으로, 정렬된 순서로 읽을 수 있다.</p>\n<h3>🪚 BST 핵심 연산</h3>\n<ul>\n<li>검색</li>\n<li>삽입</li>\n<li>삭제</li>\n<li>트리 생성, 삭제</li>\n</ul>\n<h3>🪚 시간 복잡도</h3>\n<p>노드 개수가 N개일 때,</p>\n<ul>\n<li>균등 트리: <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>l</mi><mi>o</mi><mi>g</mi><mi>N</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(logN)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\" style=\"margin-right:0.01968em;\">l</span><span class=\"mord mathnormal\">o</span><span class=\"mord mathnormal\" style=\"margin-right:0.03588em;\">g</span><span class=\"mord mathnormal\" style=\"margin-right:0.10903em;\">N</span><span class=\"mclose\">)</span></span></span></span></li>\n<li>편향 트리: <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>N</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(N)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\" style=\"margin-right:0.10903em;\">N</span><span class=\"mclose\">)</span></span></span></span></li>\n</ul>\n<blockquote>\n<p>삽입, 검색, 삭제 시간복잡도는 <strong>트리의 Depth</strong>에 비례</p>\n</blockquote>\n<p><strong>삭제의 3가지 경우</strong></p>\n<ol>\n<li>자식이 없는 리프 노드일 때 -> 그냥 삭제!</li>\n<li>자식이 1개인 노드일 때 -> 자식 노드와 교환 후, 삭제</li>\n<li>자식이 2개인 노드일 때 -> 오른쪽 자식 노드에서 가장 작은 값 또는 왼쪽 자식 노드에서 가장 큰 값과 교환 후, 삭제</li>\n</ol>\n<p>편향된 트리는 시간복잡도가 <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>N</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(N)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\" style=\"margin-right:0.10903em;\">N</span><span class=\"mclose\">)</span></span></span></span>이므로 트리를 사용할 이유가 없다!</p>\n<ul>\n<li>이를 바로 잡도록 <code class=\"language-text\">Rebalancing</code> 하는 개선방안이 <strong>AVL Tree</strong>, <strong>RedBlack Tree</strong></li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">class BinarySearchTree {\n  public class Node {\n    int data;\n    Node left;\n    Node right;\n\n    public Node(int data) {\n      this.data = data;\n      this.left = null;\n      this.right = null;\n    }\n  }\n\n  public Node root;\n  public BinarySearchTree() {\n    this.root = null;\n  }\n\n  public boolean find(int id) {\n    Node cur = root;\n\n    while(cur != null) {\n      if (cur.data == id) return true;\n      else if(cur.data &gt; id) cur = cur.left;\n      else cur = cur.right;\n    }\n\n    return false;\n  }\n\n  public boolean delete(int id) {\n    Node parent = root;\n    Node cur = root;\n    boolean isLeftChild = false;\n\n    while(cur.data != id) {\n      parent = cur;\n      if (cur.data &gt; id) {\n        isLeftChild = true;\n        cur = cur.left;\n      } else {\n        isLeftChild = false;\n        cur = cur.right;\n      }\n      if (cur == null) return false;\n    }\n\n    // case1. 자식 노드가 없는 경우 -&gt; 그냥 삭제\n    if (cur.left == null &amp;&amp; cur.right == null) {\n      if (cur == root) root = null;\n      if (isLeftChild == true) parent.left = null;\n      else parent.right = null;\n    } \n    // case2. 자식 노드가 1개인 경우 -&gt; 교환 후 삭제\n    else if (cur.right == null) {\n      if (cur == root) root = cur.left;\n      else if (isLeftChild) parent.left = cur.left;\n      else parent.right = cur.left;\n    } else if (cur.left == null) {\n      if (cur == root) root = cur.left;\n      else if (isLeftChild) parent.left = cur.right;\n      else parent.right = cur.right;\n    }\n    // case3. 자식 노드가 2개인 경우 -&gt; 오른쪽 자식 노드 중 최솟값과 교환 후 삭제\n    else if (cur.left != null &amp;&amp; cur.right != null) {\n      Node minNode = getMin(cur);\n      if (cur == root) root = minNode;\n      else if (isLeftChild) parent.left = minNode;\n      else parent.right = minNode;\n      minNode.left = cur.left;\n    }\n\n    return true;\n  }\n\n  // 오른쪽 서브 트리에서 최솟값을 반환\n  public Node getMin(Node deleteNode) {\n    Node minNode = null;\n    Node minNodeParent = null;\n    Node cur = deleleNode.right;\n\n\t\twhile(cur != null) {\n\t\t\tminNodeParent = minNode;\n\t\t\tminNode = cur;\n\t\t\tcur = cur.left;\n\t\t}\n\n\t\tif (minNode != deleleNode.right) {\n\t\t\tminNodeParent.left = minNode.right;\n\t\t\tminNode.right = deleleNode.right;\n\t\t}\n\n\t\treturn minNode;\n  }\n\n  public void insert(int id) {\n    Node newNode = new Ndoe(id);\n    if (root == null) {\n      root = newNode;\n      return;\n    }\n\n    Node cur = root;\n    Node parent = null;\n\n    while(true) {\n      parent = cur;\n\n      if (id &lt; cur.date) {\n        cur = cur.left;\n        if (cur == null) {\n          parent.left = newNode;\n          return;\n        }\n      } else {\n        cur = cur.right;\n        if (cur == null) {\n          parent.right = newNode;\n          return;\n        }\n      }\n    }\n  }\n\n  public void print(Node root) {\n    if (root != null) {\n      print(root.left);\n      System.out.println(&quot; &quot; + root.date);\n      print(root.right);\n    }\n  }\n}</code>\n        </deckgo-highlight-code>\n<hr>\n<h2>📕 참고</h2>\n<ul>\n<li><a href=\"https://gyoogle.dev/blog/computer-science/data-structure/Tree.html\">Tech Interview for developer</a></li>\n<li><a href=\"https://github.com/JaeYeopHan/Interview_Question_for_Beginner/tree/master/DataStructure#bst-binary-search-tree\">BST (Binary Search Tree)</a></li>\n</ul>","frontmatter":{"title":"📂 이진탐색트리(Binary Search Tree)","date":"May 28, 2022","update":"May 28, 2022","tags":["개발상식","Java","BST"],"series":"📂 Computer Science"},"fields":{"slug":"/[CS]이진탐색트리/","readingTime":{"minutes":4.695}}},"seriesList":{"edges":[{"node":{"id":"3fe44622-13ba-589a-bbe8-01581ea7eb50","fields":{"slug":"/[CS]배열/"},"frontmatter":{"title":"📂 배열 (Array)"}}},{"node":{"id":"5b487c3d-e474-5a07-a26c-fc8c7d7cab22","fields":{"slug":"/[CS]연결리스트/"},"frontmatter":{"title":"📂 연결 리스트 (Linked List)"}}},{"node":{"id":"57149a6b-c730-5ce4-a3c5-9cea44979c8c","fields":{"slug":"/[CS]Array&ArrayList&LinkedList/"},"frontmatter":{"title":"📂 Array vs. ArrayList vs. LinkedList"}}},{"node":{"id":"28dac540-50bf-57df-afd9-9561888e8889","fields":{"slug":"/[CS]Stack&Queue/"},"frontmatter":{"title":"📂 Stack & Queue"}}},{"node":{"id":"4c2e96a9-4c71-57e3-b8e4-220b2cdf3002","fields":{"slug":"/[CS]Heap/"},"frontmatter":{"title":"📂 Heap"}}},{"node":{"id":"44f6bf8c-3235-5ff7-9d5f-f7c816218acb","fields":{"slug":"/[CS]Trie/"},"frontmatter":{"title":"📂 Trie(트라이)"}}},{"node":{"id":"81b508c5-2689-54e4-b36f-2e8bd07e2297","fields":{"slug":"/[CS]Tree/"},"frontmatter":{"title":"📂 Tree(트리)"}}},{"node":{"id":"2efb6036-05bf-594e-b9b5-03e399be6f78","fields":{"slug":"/[CS]이진탐색트리/"},"frontmatter":{"title":"📂 이진탐색트리(Binary Search Tree)"}}},{"node":{"id":"d1ac08af-f215-5176-9cd8-df1760f4ff7e","fields":{"slug":"/[CS]BTree&B+Tree/"},"frontmatter":{"title":"📂 B Tree & B+ Tree"}}}]},"previous":{"fields":{"slug":"/[BOJ]20922/"},"frontmatter":{"title":"👩‍💻 20922. 겹치는 건 싫어"}},"next":{"fields":{"slug":"/[BOJ]16172/"},"frontmatter":{"title":"👩‍💻 16172. 나는 친구가 적다(Large)"}}},"pageContext":{"id":"2efb6036-05bf-594e-b9b5-03e399be6f78","series":"📂 Computer Science","previousPostId":"fef58615-9e18-5f50-8d09-3d1e2839342f","nextPostId":"7ca89240-c65f-5cb4-aeef-c5f1605ebd00"}},"staticQueryHashes":[]}